package com.shinow.capacitor.plusins;

import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;

import com.getcapacitor.PluginCall;

public class TTS {

    public static final String EngineLoadFailed = "引擎加载失败";
    public static final String EngineNotLoaded = "引擎未加载";
    public static final String SpeechSynthesisFailed = "语音合成失败";

    private static TextToSpeech Instance = null;

    public static void setInstance(TextToSpeech tts) {
        TTS.Instance = tts;
    }

    public static void clearInstance() {
        Instance = null;
    }

    private int getQueueMode(String QueueMode) {
        switch (QueueMode) {
            case "ADD":
                return TextToSpeech.QUEUE_ADD;
            default:
                return TextToSpeech.QUEUE_FLUSH;
        }
    }

    public void speak(PluginCall call) {
        if (Instance == null) {
            call.reject(EngineNotLoaded);
        }

        Instance.setPitch(call.getFloat("Pitch", 1.0f));
        Instance.setSpeechRate(call.getInt("Rate", 1));

        if (TextToSpeech.SUCCESS != Instance.speak(call.getString("Text", ""), getQueueMode(call.getString("QueueMode", "")), null, call.getCallbackId())) {
            call.reject(SpeechSynthesisFailed);
        }

        Instance.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onStart(String utteranceId) {
                System.out.println("TextToSpeech onStart utteranceId:" + utteranceId);
            }

            @Override
            public void onDone(String utteranceId) {
                call.resolve();
            }

            @Override
            public void onError(String utteranceId) {
                call.reject(SpeechSynthesisFailed);
            }
        });
    }

}
